package com.young.util;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {
    @Autowired
    private StringRedisTemplate redisTemplate;
    final String PRE="";
    public <K,V>boolean set(K key,V value){
        if(key==null){
            return false;
        }
        boolean res=false;
        try{
            redisTemplate.opsForValue().set(PRE+key, JSON.toJSONString(value));
            res=true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return res;
    }
    public <K,V>boolean set(K key,V value,Long timeUnit){
        if(key==null){
            return false;
        }
        boolean res=false;
        try{
            redisTemplate.opsForValue().set(PRE+key, JSON.toJSONString(value),timeUnit, TimeUnit.SECONDS);
            res=true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return res;
    }
    public <K> String get(K key){
        if(key==null){
            return null;
        }
        try{
            return redisTemplate.opsForValue().get(PRE+key);
        }catch (Exception e){
            return null;
        }
    }
}
